package com.example.springboot.controller;

import com.example.springboot.entity.WiselyMessage;
import com.example.springboot.entity.WiselyResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

@Controller
public class WsController {

    //订阅模式
    @MessageMapping("/welcome")//当浏览器向服务端发送亲求时，通过@MessageMapping映射/welcome这个地址
    @SendTo("/topic/getResponse")//当服务器有消息时，会对订阅了@SendTo中的浏览器路径发送消息
    public WiselyResponse say(WiselyMessage message)throws Exception{
        Thread.sleep(3000);
        return new WiselyResponse("Welcome,"+message.getName()+"!");
    }

    @Autowired
    private SimpMessagingTemplate messagingTemplate;//通过SimpMessagingTemplate向浏览器发送消息

    @MessageMapping("/chat")
    public void handleChat(Principal principal,String msg){//在SpringMVC中，可以直接在参数中获得principal,principal中包含当前的用户信息
        //这里是一段硬编码，如果发送人时wyf,则转发给wisely;如果发送人是wisely，则转发给wyf，实际项目中可根据需求编写
        if (principal.getName().equals("wyf")){
            messagingTemplate.convertAndSendToUser("wisely","/queue/notifications",principal.getName()+"-send"+msg);
        }else {
            messagingTemplate.convertAndSendToUser("wyf","/queue/notifications",principal.getName()+"-send"+msg);
        }
    }
}
